<template>
  <div class="app-container">
    <div>
      <!-- <el-input v-model="viewModel.Title" size="small" placeholder="标题" style="width: 200px;" class="filter-item"
        @keyup.enter.native="queryDatas" /> -->
      <!-- <el-button type="primary" size="small" @click="queryDatas" icon="el-icon-search">查询</el-button> -->
      <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">新增</el-button>
      <el-button type="primary" size="small" @click="refreshDatas" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table :data="dataList" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
      <el-table-column label="资料名字" prop="AttachmentDIsplayName" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.AttachmentDIsplayName }}</template>
      </el-table-column>
      <el-table-column label="项目名字" prop="ProjectName" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.ProjectName }}</template>
      </el-table-column>
      <el-table-column label="文件名字" prop="AttachmentName" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.AttachmentName }}</template>
      </el-table-column>
      <el-table-column label="文件大小" prop="AttachmentSize">
        <template slot-scope="scope">{{ scope.row.SizeStr }}</template>
      </el-table-column>
      <el-table-column label="文件类型" prop="AttachmentExt">
        <template slot-scope="scope">{{ scope.row.AttachmentExt }}</template>
      </el-table-column>
      <el-table-column label="创建时间" prop="CreateTime">
        <template slot-scope="scope">{{ scope.row.CreateTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;" v-if="viewModel.total>0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="viewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="viewModel.pageSize"
        @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
        :total="viewModel.total"></el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'" width="60%" top="2vh"
      :close-on-click-modal="false">
      <el-form :model="model" ref="model" :rules="rules" label-width="80px" label-position="right" style="width: 90%;">
        <el-row>
          <el-col :span="24">
            <el-form-item label="资料名称" prop="AttachmentDIsplayName">
              <el-input v-model="model.AttachmentDIsplayName" placeholder="资料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="Description">
              <el-input type="textarea" :rows="2" v-model="model.Description" placeholder="描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资源" prop="AttachmentUrl">
              <el-input style="width: 80%;float: left;" v-model="model.AttachmentUrl" placeholder="资源" />
              <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false" :on-success="handleSuccess"
                :before-upload="beforeUpload">
                <el-button type="primary" v-loading='uploading' size="mini">上传资源</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="排序号" prop="SortNum">
              <el-input-number v-model="model.SortNum" style="width: 100%;" :step="1" step-strictly :min="0">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmModel">提交</el-button>
      </div>
      <input type="text" ref="dur" name="22" v-show="false" />
    </el-dialog>

  </div>

</template>

<style>
  .avatar-uploader .el-upload {
    border: none;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: 15px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .v-modal {
    z-index: 2000 !important;
  }
</style>

<script>
  import { updateData, deleteData, getDataList, addData } from '@/api/project'
  import { deepClone } from "@/utils";

  const defaultModel = {
    ID: '',
    TeachingID: '',
    AttachmentDIsplayName: '',
    AttachmentName: '',
    AttachmentUrl: '',
    AttachmentSize: '',
    AttachmentExt: '',
    Description: '',
    Duration: '',
    SortNum: '',
    DownloadUrl: '',
    Creater: '',
    CreateTime: '',
    Modify: '',
    ModifyTime: ''
  }
  export default {
    data() {
      return {
        viewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          Title: '',
          ProjectId: '',
          OrderBy: 'CreateTime',//排序字段
          IsAsc: 'false', //是否升序
          SortDir: 'DESC'
        },
        randomNum: '',
        roleList: [],
        loading: false,
        uploading: false,
        upDialogFormVisible: false,
        dialogVisible: false,
        dialogType: '',
        model: Object.assign({}, defaultModel),
        dataList: [],
        apiPre: process.env.VUE_APP_BASE_API,
        actionUrl: '',
        rules: {
          Title: [
            { required: true, message: "请输入项目名字", trigger: "blur" },
            {
              min: 1,
              max: 100,
              message: "长度在 1 到 100 个字符",
              trigger: "blur"
            }
          ]
        }
      }
    },
    computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存

    },
    created() {  // 实例创建完成后执行的代码
      this.viewModel.ProjectId = this.$route.params && this.$route.params.id
      this.getList(this.viewModel);
      this.actionUrl = this.apiPre + '/Upload/UploadFiles'
    },
    methods: {
      beforeUpload(file) {
        this.uploading = true
        var fileName = file.name || ''
        var ext = fileName.split('.')[fileName.split('.').length - 1]
        if (ext == 'mp4') {
          var url = URL.createObjectURL(file)
          var audioElement = new Audio(url)
          var ele = this.$refs.dur
          var d
          audioElement.addEventListener('loadedmetadata', function (_event) {
            d = audioElement.duration
            ele.name = d
          })
          this.model.Duration = ele.name
        }
        this.model.AttachmentName = fileName
        this.model.AttachmentExt = ext
        this.model.AttachmentSize = parseFloat(file.size / 1024).toFixed(4)
      },
      handleSuccess(res, file) {//资源上传成功响应方法
        this.model.AttachmentUrl = res.data
        this.model.DownloadUrl = res.data
        this.uploading = false
        this.$notify({
          title: "成功",
          message: "上传成功!",
          type: "success",
          duration: 3000
        });
      },
      closeupDialog() {
        this.upDialogFormVisible = false;
        this.queryDatas();
      },
      async getList(viewModel) {
        this.loading = true
        const res = await getDataList(viewModel);
        if (res.data) {
          this.viewModel.total = res.data.TotalCount;
        }
        this.dataList = res.data.Items;
        this.loading = false
      },
      queryDatas() {
        this.viewModel.page = 1
        this.getList(this.viewModel);
      },
      refreshDatas() {
        this.viewModel.Title = '';
        this.viewModel.SubTitle = '';
        this.viewModel.States = '-1';
        this.viewModel.page = 1
        this.getList(this.viewModel);
      },
      sortChange(data) {
        const { prop, order } = data
        this.viewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.viewModel.OrderBy = "CreateTime"
        if (order === 'ascending') {
          this.viewModel.SortDir = 'ASC'
        } else {
          this.viewModel.SortDir = 'DESC'
        }
        this.queryDatas()
      },
      lastPage(val) {
        this.viewModel.page = val;
      },
      nextPage(val) {
        this.viewModel.page = val;
      },
      handleChange(value) {
        console.log(value);
      },
      handleSizeChange(val) {
        this.viewModel.pageSize = val;
        this.getList(this.viewModel);
      },
      handleCurrentChange(val) {
        this.viewModel.page = val
        this.getList(this.viewModel)
      },
      handleAdd() {
        this.dialogType = 'new';
        this.dialogVisible = true;
        this.model = deepClone(defaultModel)
        this.model.TeachingID = this.viewModel.ProjectId
        this.$nextTick(() => {
          this.$refs['model'].clearValidate() //清空上次的错误验证提示
        })

      },
      handleEdit(scope) {
        this.dialogType = 'edit';
        this.dialogVisible = true;
        this.model = Object.assign({}, scope.row);
        this.$nextTick(() => {
          this.$refs['model'].clearValidate() //清空上次的错误验证提示
        });
      },
      async confirmModel() {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs['model'].validate(valid => {
          v = valid;
        });
        if (!v) {
          return false;
        }
        const isEdit = this.dialogType === 'edit';
        var res
        if (isEdit) {
          res = await updateData(this.model);
        } else {
          res = await addData(this.model)
          this.viewModel.page = 1
        }
        if (res && !res.data) {
          this.$notify({
            title: "失败",
            type: "error",
            message: res.message
          });
          return
        }
        this.getList(this.viewModel);
        this.model = deepClone(defaultModel)
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      },
      handleDelete({ $index, row }) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await deleteData(row.ID, this.viewModel.ProjectId);
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
            this.getList(this.viewModel);
          })
          .catch(err => {
            console.error(err);
          });
      },
      handleAvatarSuccess(res, file) {//图片上传成功响应方法
        this.model.ImageURL = res.data;
      },
      beforeAvatarUpload(file) {
        const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isImg) {
          this.$notify({
            title: "失败",
            message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
            type: "error",
            duration: 3000
          });
          return false
        }
        if (!isLt2M) {
          this.$notify({
            title: "失败",
            message: "上传头像图片大小不能超过 4MB!",
            type: "error",
            duration: 3000
          });
          return false
        }
        return true
      }
    }
  }
</script>